package com.tanhua.dubbo.api.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.pojo.TimeLine;
import com.tanhua.dubbo.pojo.Users;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 写入好友的时间线
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Async //底层：会开一个线程去执行
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId) {
        //查询好友列表
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Users> usersList = this.mongoTemplate.find(query, Users.class);
        if (CollUtil.isEmpty(usersList)) {
            //返回成功
            return CompletableFuture.completedFuture("ok");
        }

        //TODO 写入到自己的时间线表

        //遍历好友关系集合
        for (Users users : usersList) {
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setPublishId(publishId);
            timeLine.setUserId(userId);
            timeLine.setDate(System.currentTimeMillis());

            //给好友写入
            this.mongoTemplate.save(timeLine, "quanzi_time_line_" + users.getFriendId());
        }

        return CompletableFuture.completedFuture("ok");
    }
}
